<?php
namespace App\Admin\Controllers\Ext;

class Attach
{
    /**
     * add a grid here.
     */
    public function grid($grid,array $app)
    {
			$grid->model()->withCount(['attaches']);
			$grid->column('attaches_count', '附件数');
	}

    /**
     * add a form here.
     */
    public function form($form,array $app)
    {
			
			$uid=\Illuminate\Support\Facades\Auth::guard('admin')->user()->user_id;
			//$uid=\Illuminate\Support\Facades\Auth::guard()->user()->user_id;
			$form->hasMany('attaches', '', function (\Encore\Admin\Form\NestedForm $form) use($app,$uid){
				$sets = $app['sets']['attach'] ?? [];
				
				$maxsize = $app['sets']['attach']['maxsize'] ?? config('exts.attach.sets.maxsize');
			    $ext = $app['sets']['attach']['ext'] ?? config('exts.attach.sets.ext');
				$options['maxFileSize']= $maxsize;
				$options['allowedFileExtensions'] = str2arr($ext);
				$options['showPreview']=false;

				$form->hidden('app_name')->default($app['name']);
				$form->file('file','附件添加')->options($options)->required();
				if(!empty($sets['note'])){
					$form->text('note','附件说明');
				}
				$form->hidden('user_id')->default($uid);
			})->mode('table');
    }

    public function show($show,array $app)
    {
			$show->field('attaches','附件')->unescape()->as(function ($attaches) {
				$str = "<div>";
				foreach($attaches as $attach){
					if( !empty($attach['title']) ){
						$str .= "<h3>".$attach['title']."</h3>";
					}
					if( !empty($attach['cover']) ){
						$str .= "<p><img src='/upload/small/".$attach['cover']."' /></p>";
					}
					if( !empty($attach['attach']) ){
						if($attach['type'] == 'image'){
							$str .= "<p><img src='/upload/small/".$attach['attach']."' /></p>";
						}else{
							$str .= "<p><a href='/upload/{$attach['attach']}'>{$attach['attach']}</a></p>";
						}
					}	
					if( !empty($attach['attaches']) ){
						foreach($attach['attaches'] as $k=>$att){
							if($attach['type'] == 'images'){
								$str .= "<img src='/upload/small/{$att}' />";
							}else{
								$str .= "<p>文件: <a href='/upload/{$att}'>{$att}</a></p>";
							}
						}
						$str .= "<hr />";
					}				
					if(!empty($attach['url']) ){
						$str .= "链接: <p><a href='/upload/{$attach['url']}'>{$attach['title']}</a></p>";
					}
					if( !empty($attach['note']) ){
						$str .= "<p>".$attach['note']."</p>";
					}
				}				
				$str .= "</div>";
				return $str;
			});
	}
}